package ui.accountbook;

import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import tool.LongStringTransformer;
import tool.MyButton;
import tool.MyLabel;
import vo.AccountBookVo;
import vo.AccountorVo;
import vo.ClientVo;
import vo.CommodityTypeVo;
import vo.CommodityVo;
import vo.UserVo;
import vo.Vo;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;

import o.客户类型;
import client.boot.BLServiceManager;
import blservice.accountbook.AccountBookBLService;
import blservice.client.ClientBLService;
import blservice.commodity.CommodityBLService;
import blservice.commodity.CommodityTypeBLService;
import blservice.finance.AccountorBLService;
import java.awt.Color;

public class AccountBookInfoDialog extends JDialog {
	private static final long serialVersionUID = -6732109876134457428L;
	private AccountBookVo ab;
	private AccountBookManagePanel father;
	private UserVo user;
	private boolean isNewAccountBook;
	private JTable tableCommodity;
	private JScrollPane jspCommodity;
	private JTable tableClient;
	private JScrollPane jspClient;
	private JTable tableAccount;
	private JScrollPane jspAccount;
	private JTable tableCommodityType;
	private JScrollPane jspCommodityType;
	private JTextField nameTF;

	public AccountBookInfoDialog(boolean isNewAccountBook, UserVo user,
			AccountBookManagePanel father, AccountBookVo ab) {
		getContentPane().setBackground(Color.ORANGE);
		if (ab == null) {
			ab = new AccountBookVo();
		}
		this.ab = ab;
		this.isNewAccountBook = isNewAccountBook;
		this.user = user;
		this.father = father;

		this.setBounds(0, 0, 1200, 600);
		getContentPane().setLayout(null);
		if (isNewAccountBook) {
			this.setTitle("新建账目");
		} else {
			this.setTitle("账目信息");
		}
		tableAccount = new JTable() {
			private static final long serialVersionUID = -6618385954857081411L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return isNewAccountBook;
			}
		};
		jspAccount = new JScrollPane(tableAccount);
		jspAccount.setBounds(819, 319, 355, 199);
		getContentPane().add(jspAccount);
		tableCommodity = new JTable() {
			private static final long serialVersionUID = -8061809438321377773L;

			@Override
			public boolean isCellEditable(int row, int column) {
				if (isNewAccountBook) {
					if (column == 1 || column == 4 || column == 7
							|| column == 8) {
						return false;
					} else {
						return true;
					}
				} else {
					return false;
				}
			}
		};
		jspCommodity = new JScrollPane(tableCommodity);
		jspCommodity.setLocation(10, 65);
		jspCommodity.setSize(799, 219);
		getContentPane().add(jspCommodity);
		tableClient = new JTable() {
			private static final long serialVersionUID = -3966193923552261410L;

			@Override
			public boolean isCellEditable(int row, int column) {
				if (isNewAccountBook) {
					if (column == 0 || column == 9 || column == 10
							|| column == 11) {
						return false;
					} else {
						return true;
					}
				} else {
					return false;
				}
			}
		};
		jspClient = new JScrollPane(tableClient);
		jspClient.setLocation(10, 319);
		jspClient.setSize(799, 232);
		getContentPane().add(jspClient);

		tableCommodityType = new JTable() {
			private static final long serialVersionUID = -5776463005709271388L;

			@Override
			public boolean isCellEditable(int row, int column) {
				if (isNewAccountBook) {
					if (column == 0) {
						return false;
					} else {
						return true;
					}
				} else {
					return false;
				}
			}

		};
		jspCommodityType = new JScrollPane(tableCommodityType);
		jspCommodityType.setBounds(819, 65, 355, 219);
		getContentPane().add(jspCommodityType);

		JLabel label = new MyLabel("商品信息");
		label.setBounds(10, 40, 68, 15);
		getContentPane().add(label);

		JLabel label_1 = new MyLabel("客户信息");
		label_1.setBounds(10, 294, 68, 15);
		getContentPane().add(label_1);

		JLabel label_2 = new MyLabel("银行账户信息");
		label_2.setBounds(819, 294, 126, 15);
		getContentPane().add(label_2);

		JLabel label_3 = new MyLabel("账目名称");
		label_3.setBounds(10, 13, 68, 15);
		getContentPane().add(label_3);

		nameTF = new JTextField();
		nameTF.setBounds(74, 10, 133, 21);
		nameTF.setEditable(this.isNewAccountBook);
		nameTF.setText(ab.getName());
		getContentPane().add(nameTF);
		nameTF.setColumns(10);

		JButton commodityAdd = new MyButton("Graphics/Button51-23.png");
		commodityAdd.setText("+");
		commodityAdd.setBounds(758, 36, 51, 23);
		commodityAdd.setVisible(this.isNewAccountBook);
		commodityAdd.addActionListener(e -> addNewLineCommodity());
		getContentPane().add(commodityAdd);

		JButton clientAdd = new MyButton("Graphics/Button51-23.png");
		clientAdd.setText("+");
		clientAdd.setBounds(758, 290, 51, 23);
		clientAdd.setVisible(this.isNewAccountBook);
		clientAdd.addActionListener(e -> addNewLineClient());
		getContentPane().add(clientAdd);

		JButton accountAdd = new MyButton("Graphics/Button51-23.png");
		accountAdd.setText("+");
		accountAdd.setBounds(1123, 290, 51, 23);
		accountAdd.setVisible(this.isNewAccountBook);
		accountAdd.addActionListener(e -> addNewLineAccount());
		getContentPane().add(accountAdd);

		JButton confirm = new MyButton("Graphics/Button93-23.png");
		confirm.setText("确定");
		confirm.setBounds(978, 528, 93, 23);
		confirm.setVisible(this.isNewAccountBook);
		confirm.addActionListener(e -> confirm());
		getContentPane().add(confirm);

		JButton close = new MyButton("Graphics/Button93-23.png");
		close.setText("关闭");
		close.setBounds(1081, 528, 93, 23);
		close.addActionListener(e -> {
			father.showAll();
			this.dispose();
		});
		getContentPane().add(close);

		JLabel label_4 = new MyLabel("商品分类信息");
		label_4.setBounds(819, 40, 104, 15);
		getContentPane().add(label_4);

		JButton commodityTypeAdd = new MyButton("Graphics/Button51-23.png");
		commodityTypeAdd.setText("+");
		commodityTypeAdd.setBounds(1123, 36, 51, 23);
		commodityTypeAdd.addActionListener(e -> addNewLineCommodityType());
		commodityTypeAdd.setVisible(this.isNewAccountBook);
		getContentPane().add(commodityTypeAdd);

		JLabel label_5 = new MyLabel("注意：不符合格式的数据将会被清空");
		label_5.setVisible(this.isNewAccountBook);
		label_5.setBounds(819, 13, 355, 15);
		getContentPane().add(label_5);
		
		JButton importAllBtn = new MyButton("Graphics/Button93-23.png");
		importAllBtn.setText("一键导入");
		importAllBtn.setBounds(875, 528, 93, 23);
		importAllBtn.setVisible(this.isNewAccountBook);
		importAllBtn.addActionListener(e->importAll());
		getContentPane().add(importAllBtn);

		display();
	}

	private void confirm() {
		if(nameTF.getText().equals("")){
			JOptionPane.showMessageDialog(this, "账目名称不能为空");
		}
		ab.setName(nameTF.getText());
		freshAccountData();
		freshClientData();
		freshCommodityData();
		freshCommodityTypeData();

		try {
			AccountBookBLService bl = BLServiceManager
					.getAccountBookBLService();
			Vo result = bl.add(ab);
			if (result.isSuccessed()) {
				JOptionPane.showMessageDialog(this, "期初建账成功，请重启服务器");
				father.showAll();
				this.dispose();
			} else {
				JOptionPane.showMessageDialog(this,
						"期初建账失败\n" + result.getFailMessage());
			}
		} catch (RemoteException | MalformedURLException | NotBoundException
				| SQLException e) {
			JOptionPane.showMessageDialog(this, "无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}
	}

	private void freshClientData() {
		ab.get客户信息().clear();
		for (int i = 0; i < tableClient.getRowCount(); i++) {
			String classify = (String) tableClient.getValueAt(i, 1);
			if (!classify.equals("进货商") && !classify.equals( "销售商")) {
				continue;
			}
			int level = 0;
			try {
				level = Integer.parseInt((String) tableClient.getValueAt(i, 2));
			} catch (NumberFormatException e) {
				continue;
			}
			String name = (String) tableClient.getValueAt(i, 3);
			String tel = (String) tableClient.getValueAt(i, 4);
			String address = (String) tableClient.getValueAt(i, 5);
			String postcode = (String) tableClient.getValueAt(i, 6);
			String mail = (String) tableClient.getValueAt(i, 7);
			long receivable = 0;
			try {
				receivable = LongStringTransformer
						.StringToLong((String) tableClient.getValueAt(i, 8));
			} catch (NumberFormatException e) {
				continue;
			}

			ClientVo addVo = new ClientVo();
			addVo.setOperator(user.getName());
			addVo.setOperation("添加客户");
			addVo.set地址(address);
			addVo.set姓名(name);
			addVo.set邮编(postcode);
			addVo.set应付(0);
			addVo.set应收(0);
			addVo.set应收额度(receivable);
			addVo.set电子邮箱(mail);
			addVo.set电话(tel);
			addVo.set类型(客户类型.valueOf(classify));
			addVo.set级别(level);
			addVo.set默认业务员("");
			ab.get客户信息().add(addVo);
		}
	}

	private void freshCommodityTypeData() {
		ab.get商品分类信息().clear();
		for (int i = 0; i < tableCommodityType.getRowCount(); i++) {
			if (!((String) tableCommodityType.getValueAt(i, 1)).equals("")) {
				CommodityTypeVo temp = new CommodityTypeVo();
				temp.set名称((String) tableCommodityType.getValueAt(i, 1));
				temp.set父节点((String) tableCommodityType.getValueAt(i, 2));
				ab.get商品分类信息().add(temp);
			}
		}
	}

	private void freshCommodityData() {
		ab.get商品信息().clear();
		for (int i = 0; i < tableCommodity.getRowCount(); i++) {
			String belongTo = (String) tableCommodity.getValueAt(i, 0);
			String name = (String) tableCommodity.getValueAt(i, 2);
			String type = (String) tableCommodity.getValueAt(i, 3);
			int stocknum = 0;
			long importprice = 0;
			if (name.equals("")) {
				continue;
			}
			try {
				importprice = LongStringTransformer
						.StringToLong((String) tableCommodity.getValueAt(i, 5));
			} catch (NumberFormatException e) {
				continue;
			}
			long saleprice = 0;
			try {
				saleprice = LongStringTransformer
						.StringToLong((String) tableCommodity.getValueAt(i, 6));
			} catch (NumberFormatException e) {
				continue;
			}
			int warningvalue = 0;

			try {
				warningvalue = Integer.parseInt((String) tableCommodity
						.getValueAt(i, 9));
			} catch (NumberFormatException e) {
				continue;
			}
			CommodityVo addVo = new CommodityVo();
			addVo.setOperator(user.getName());
			addVo.setOperation("添加商品");
			addVo.setBelongTo(belongTo);
			addVo.setName(name);
			addVo.set型号(type);
			addVo.setstocknum(stocknum);
			addVo.set进价(importprice);
			addVo.set售价(saleprice);
			addVo.set库存数量警戒值(warningvalue);
			addVo.setOperation("增加商品");
			ab.get商品信息().add(addVo);
		}
	}

	private void freshAccountData() {
		ab.get银行账户信息().clear();
		for (int i = 0; i < tableAccount.getRowCount(); i++) {
			AccountorVo temp = new AccountorVo();
			temp.set名称((String) tableAccount.getValueAt(i, 0));
			try {
				temp.set金额(tool.LongStringTransformer
						.StringToLong((String) tableAccount.getValueAt(i, 1)));
			} catch (NumberFormatException e) {
				continue;
			}
			ab.get银行账户信息().add(temp);
		}
	}

	private void addNewLineCommodity() {
		freshCommodityData();
		ab.get商品信息().add(new CommodityVo());
		displayCommodity();
	}

	private void addNewLineClient() {
		freshClientData();
		ab.get客户信息().add(new ClientVo());
		displayClient();
	}

	private void addNewLineAccount() {
		freshAccountData();
		ab.get银行账户信息().add(new AccountorVo());
		displayAccount();
	}

	private void addNewLineCommodityType() {
		freshCommodityTypeData();
		ab.get商品分类信息().add(new CommodityTypeVo());
		displayCommodityType();
	}

	void display() {
		displayCommodityType();
		displayCommodity();
		displayAccount();
		displayClient();
	}

	private void displayClient() {
		Vector<String> columnNames = new Vector<String>();
		columnNames.add("编号");
		columnNames.add("分类");
		columnNames.add("级别");
		columnNames.add("姓名");
		columnNames.add("电话");
		columnNames.add("地址");
		columnNames.add("邮编");
		columnNames.add("电子邮箱");
		columnNames.add("应收额度");
		columnNames.add("应收");
		columnNames.add("应付");
		columnNames.add("默认业务员");

		Vector<Vector<String>> rowData = new Vector<Vector<String>>();
		Vector<String> clientInfo;
		List<ClientVo> clientItem = ab.get客户信息();
		for (int i = 0; i < clientItem.size(); i++) {
			clientInfo = new Vector<String>();
			clientInfo.add(clientItem.get(i).get编号());
			if (clientItem.get(i).get类型() == null) {
				clientInfo.add("");
			} else {
				clientInfo
						.add(String.valueOf(clientItem.get(i).get类型().name()));
			}
			clientInfo.add(String.valueOf(clientItem.get(i).get级别()));
			clientInfo.add(clientItem.get(i).get姓名());
			clientInfo.add(clientItem.get(i).get电话());
			clientInfo.add(clientItem.get(i).get地址());
			clientInfo.add(clientItem.get(i).get邮编());
			clientInfo.add(clientItem.get(i).get电子邮箱());
			clientInfo.add(tool.LongStringTransformer.LongToString(clientItem.get(i).get应收额度()));
			clientInfo.add(tool.LongStringTransformer.LongToString(clientItem.get(i).get应收()));
			clientInfo.add(tool.LongStringTransformer.LongToString(clientItem.get(i).get应付()));
			clientInfo.add(clientItem.get(i).get默认业务员());
			rowData.add(clientInfo);
		}

		tableClient.setModel(new DefaultTableModel(rowData, columnNames));
		if(isNewAccountBook){
			tableClient.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox<String>(new String[]{"进货商","销售商"})));
			tableClient.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(new JComboBox<String>(new String[]{"0","1","2","3","4"})));
		}
	}

	private void displayAccount() {
		List<AccountorVo> accounts = ab.get银行账户信息();

		tableAccount.setModel(new DefaultTableModel(readAccountVo(accounts),
				new String[] { "名称", "金额" }));
	}

	private String[][] readAccountVo(List<AccountorVo> account) {
		String[][] result = new String[account.size()][2];
		for (int i = 0; i < result.length; i++) {
			result[i][0] = account.get(i).get名称();
			result[i][1] = tool.LongStringTransformer.LongToString(account.get(
					i).get金额());
		}
		return result;
	}

	private void displayCommodity() {
		Vector<Vector<String>> rowData = new Vector<Vector<String>>();
		Vector<String> commodityInfo;
		List<CommodityVo> commodityItem = ab.get商品信息();
		for (int i = 0; i < commodityItem.size(); i++) {
			commodityInfo = new Vector<String>();
			commodityInfo.add(commodityItem.get(i).belongTo);
			commodityInfo.add(commodityItem.get(i).编号);
			commodityInfo.add(commodityItem.get(i).name);
			commodityInfo.add(commodityItem.get(i).型号);
			commodityInfo.add(Integer.toString(commodityItem.get(i).stocknum));
			commodityInfo.add(LongStringTransformer.LongToString(commodityItem
					.get(i).进价));
			commodityInfo.add(LongStringTransformer.LongToString(commodityItem
					.get(i).售价));
			commodityInfo.add(LongStringTransformer.LongToString(commodityItem
					.get(i).最近进价));
			commodityInfo.add(LongStringTransformer.LongToString(commodityItem
					.get(i).最近售价));
			commodityInfo.add(Integer.toString(commodityItem.get(i).库存数量警戒值));
			rowData.add(commodityInfo);

		}

		Vector<String> columnNames = new Vector<String>();
		columnNames.add("所属分类");
		columnNames.add("编号");
		columnNames.add("名称");
		columnNames.add("型号");
		columnNames.add("库存数量");
		columnNames.add("进价");
		columnNames.add("零售价");
		columnNames.add("最近进价");
		columnNames.add("最近零售价");
		columnNames.add("库存警戒值");

		tableCommodity.setModel(new DefaultTableModel(rowData, columnNames));
	}

	private void displayCommodityType() {
		Vector<String> columnNames = new Vector<String>();
		columnNames.add("编号");
		columnNames.add("名称");
		columnNames.add("父节点");

		Vector<Vector<String>> rowData = new Vector<Vector<String>>();
		Vector<String> commodityTypeInfo;
		List<CommodityTypeVo> commodityTypeItem = ab.get商品分类信息();
		for (int i = 0; i < commodityTypeItem.size(); i++) {
			commodityTypeInfo = new Vector<String>();
			commodityTypeInfo.add(commodityTypeItem.get(i).编号);
			commodityTypeInfo.add(commodityTypeItem.get(i).名称);
			commodityTypeInfo.add(commodityTypeItem.get(i).父节点);
			rowData.add(commodityTypeInfo);
		}
		tableCommodityType
				.setModel(new DefaultTableModel(rowData, columnNames));
	}
	
	private void importAll(){		
		try {
			AccountBookBLService abbl=BLServiceManager.getAccountBookBLService();
			AccountBookVo abd=abbl.getDefaultAccountBook();
			AccountorBLService abl=BLServiceManager.getAccountorBLService(abd);
			ClientBLService cbl=BLServiceManager.getClientBLService(abd);
			CommodityBLService cmbl=BLServiceManager.getCommodityBLService(abd);
			CommodityTypeBLService ctbl=BLServiceManager.getCommodityTypeBLService(abd);
			ab.set商品信息(cmbl.getAll());
			ab.set商品分类信息(ctbl.getAll());
			ab.set客户信息(cbl.getAll());
			ab.set银行账户信息(abl.getAll());
			display();
		} catch (RemoteException | MalformedURLException | NotBoundException
				| SQLException e) {
			JOptionPane.showMessageDialog(this, "无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}
	}
}
